<script setup>
import { ref, nextTick } from 'vue'
import { addAnnouncementService, updateAnnouncementService } from '@/api/announcement.js'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

// 控制抽屉的显示与隐藏
const visibleDrawer = ref(false)

const defaultDTO = {
  title: null, // 标题
  content: '<p></p>' // 内容
}

const announcementDTO = ref({ ...defaultDTO })

// 向外暴露方法
const open = (row) => {
  visibleDrawer.value = true // 打开抽屉
  if (row.id) {
    const { id, title, content } = row
    announcementDTO.value = { id, title, content }
  } else {
    announcementDTO.value = { ...defaultDTO }
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (announcementDTO.value.id) {
    await updateAnnouncementService(announcementDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
    visibleDrawer.value = false
  } else {
    await addAnnouncementService(announcementDTO.value)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
    visibleDrawer.value = false
  }
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDrawer.value = false
  nextTick(() => {
    announcementDTO.value = { ...defaultDTO }
  })
  // announcementDTO.value = { ...defaultDTO }
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="announcementDTO.id ? '修改公告信息' : '新增公告'">
    <el-form :model="announcementDTO" ref="formRef" label-width="auto">
      <el-form-item label="标题" prop="title">
        <el-input v-model="announcementDTO.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div class="editor">
          <quill-editor
            :key="announcementDTO.id || 'new'"
            v-model:content="announcementDTO.content"
            content-type="html"
            theme="snow"
            placeholder="请输入内容"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
        <el-button type="info" plain @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
